import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author zhouyanxiang
 * @create 2020-11-2020/11/1-12:14
 * <h1>加权随机法</h1>
 */
public class Solution {

    static Map<String, Integer> map = new ConcurrentHashMap<>();

    static {
        map.put("192.168.1.12",1);
        map.put("192.168.1.13",2);
        map.put("192.168.1.14",4);
    }

    public String random() {
        Map<String, Integer> ipMap = new ConcurrentHashMap<>(map);
        Set<String> set = ipMap.keySet();
        List<String> list = new ArrayList<>();

        for (String serverName : set) {
            Integer weight = ipMap.get(serverName);
            for (int i = 0; i < weight; i++) {
                list.add(serverName);
            }
        }
        Random random = new Random();
        int pos = random.nextInt(list.size());
        return list.get(pos);
    }

    public static void main(String[] args) {
        Solution s = new Solution();
        for (int i = 0; i < 10; i++) {
            System.out.println(s.random());
        }
    }
}
